package com.hongxing.baseaar.base

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import androidx.viewbinding.ViewBinding
import com.hongxing.baseaar.R
import java.lang.reflect.ParameterizedType

abstract class BaseDialogFragment<VB : ViewBinding>() : DialogFragment() {
    lateinit var binding: VB

    // protected var api = RetrofitHelp.get().getApiServices(ApiService::class.java)
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        this.dialog!!.requestWindowFeature(Window.FEATURE_NO_TITLE)
        val window: Window? = this.dialog!!.window
        //去掉dialog默认的padding
        window!!.decorView.setPadding(0, 0, 0, 0)
        window.decorView.setBackgroundResource(R.color.transparent)
        val lp: WindowManager.LayoutParams = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        dialog?.setCancelable(isCancelOutDismiss())
        dialog?.setCanceledOnTouchOutside(isCancelOutDismiss())
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        window.attributes = lp
        val superClass = javaClass.genericSuperclass
        if (superClass is ParameterizedType) {
            val clazz = superClass.actualTypeArguments[0] as Class<VB>
            val method = clazz.getDeclaredMethod("inflate", LayoutInflater::class.java)
            binding = method.invoke(null, layoutInflater) as VB
        }
        dialog!!.setCanceledOnTouchOutside(true)
        initView(requireContext())
        return binding.root
    }


    abstract fun initView(requireContext: Context)
    open fun isCancelOutDismiss(): Boolean {
        return true
    }
}